# -*- coding: utf-8 -*-
import ast
import json
import math

import requests
from PyQt5.QtGui import QPixmap, QBrush, QColor, QFont
from PyQt5.QtWidgets import QWidget, QMessageBox, QLabel, QHeaderView, QVBoxLayout, QTableWidgetItem, QAbstractItemView, \
    QGraphicsScene, QGraphicsPixmapItem, QLineEdit, QComboBox, QDateEdit, QFileDialog, QHBoxLayout, QPushButton, QDialog
from PyQt5.QtCore import Qt, QRect, pyqtSignal, QDir, QDate

from ImageUploaderThread import ImageUploaderThread
from aysncImageLoader import AsyncImageLoader
from ui import add
import constant
from utils import api


class AddWindow(QWidget, add.Ui_form):
    imgCol = 3
    window_closed = pyqtSignal()

    def __init__(self, token=None, id=0, clickedFun=None):
        super().__init__()
        self.setupUi(self)
        self.token = token
        self.graphicsView.hide()
        self.setWindowTitle(constant.APP_NAME)
        self.uploadSuccess = []
        self.id = id
        self.clickedFun = clickedFun

        font = QFont()
        font.setFamily("宋体")
        font.setPixelSize(10)
        self.tableWidget.setFont(font)
        print('clickedFun: ' + clickedFun)
        print("add window: " + str(id))

        if clickedFun == 'btn_fangDetail_click':
            self.setWindowTitle(constant.APP_NAME + '-房屋详情')
            self.getFangDetail()
        elif clickedFun == 'btn_areaDetail_click':
            self.setWindowTitle(constant.APP_NAME + '-小区详情')
            self.getAreaDetail()
        elif clickedFun == 'btn_areaAdd_click':
            self.setWindowTitle(constant.APP_NAME + '-添加小区')
            self.addArea()
        elif clickedFun == 'btn_areaEdit_click':
            self.setWindowTitle(constant.APP_NAME + '-编辑小区')
            self.editArea()

    def addArea(self):
        try:
            url = constant.API_HOST + '/setting/area_setting'
            res = api.get(self, url)
            if res is not None and res['code'] == 0:
                areaType = res['data']['area_type']
                limitYear = res['data']['limit_year']
                buildType = res['data']['build_type']

                tableWidget = self.tableWidget
                tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                tableWidget.setRowCount(3)
                tableWidget.setColumnCount(6)
                tableWidget.setWordWrap(True)

                for i in range(len(tableWidget.horizontalHeader())):
                    if i % 2 == 0:
                        tableWidget.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

                tableWidget.setItem(0, 0, QTableWidgetItem('小区名称：'))
                self.input_add_areaName = QLineEdit()
                self.input_add_areaName.setObjectName("input_add_areaName")
                tableWidget.setCellWidget(0, 1, self.input_add_areaName)
                tableWidget.setItem(0, 2, QTableWidgetItem('物业类型：'))
                self.input_add_areaType = QComboBox()
                for item in areaType:
                    self.input_add_areaType.addItem(item)
                self.input_add_areaType.setObjectName("input_add_areaType")
                tableWidget.setCellWidget(0, 3, self.input_add_areaType)
                tableWidget.setItem(0, 4, QTableWidgetItem('竣工时间：'))
                self.input_add_finishTime = QDateEdit()
                self.input_add_finishTime.setObjectName("input_add_finishTime")
                tableWidget.setCellWidget(0, 5, self.input_add_finishTime)
                tableWidget.setItem(1, 0, QTableWidgetItem('产权年限：'))
                self.input_add_limitYear = QComboBox()
                for item in limitYear:
                    self.input_add_limitYear.addItem(item)
                self.input_add_limitYear.setObjectName("input_add_limitYear")
                tableWidget.setCellWidget(1, 1, self.input_add_limitYear)
                tableWidget.setItem(1, 2, QTableWidgetItem('建筑类型：'))
                self.input_add_buildType = QComboBox()
                for item in buildType:
                    self.input_add_buildType.addItem(item)
                self.input_add_buildType.setObjectName("input_add_buildType")
                tableWidget.setCellWidget(1, 3, self.input_add_buildType)
                tableWidget.setItem(1, 4, QTableWidgetItem('开发商：'))
                self.input_add_areaBuilder = QLineEdit()
                self.input_add_areaBuilder.setObjectName("input_add_areaBuilder")
                tableWidget.setCellWidget(1, 5, self.input_add_areaBuilder)
                tableWidget.setItem(2, 0, QTableWidgetItem('小区地址：'))
                tableWidget.setSpan(2, 1, 1, 5)
                self.input_add_areaAddress = QLineEdit()
                self.input_add_areaAddress.setObjectName("input_add_areaAddress")
                tableWidget.setCellWidget(2, 1, self.input_add_areaAddress)
                tableWidget.resizeRowsToContents()

                self.btn_upload_area.clicked.connect(lambda _, uploadType='area': self.upload_images(uploadType))
                self.btn_submit_area.clicked.connect(self.btn_submit_area_click)
                self.btn_cancel_area.clicked.connect(self.btn_cancel_area_click)


        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def editArea(self):
        try:
            url = constant.API_HOST + '/setting/area_setting'
            res = api.get(self, url)
            if res is not None and res['code'] == 0:
                areaType = res['data']['area_type']
                limitYear = res['data']['limit_year']
                buildType = res['data']['build_type']

                url = constant.API_HOST + '/setting/area_detail'
                data = {
                    'id': self.id
                }
                res = api.get(self, url, data)
                if res is not None and res['code'] == 0:
                    areaDict = res['data']

                    tableWidget = self.tableWidget
                    tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    tableWidget.setRowCount(3)
                    tableWidget.setColumnCount(6)
                    tableWidget.setWordWrap(True)

                    for i in range(len(tableWidget.horizontalHeader())):
                        if i % 2 == 0:
                            tableWidget.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

                    tableWidget.setItem(0, 0, QTableWidgetItem('小区名称：'))
                    self.input_add_areaName = QLineEdit()
                    self.input_add_areaName.setObjectName("input_add_areaName")
                    self.input_add_areaName.setText(areaDict['area_name'])
                    tableWidget.setCellWidget(0, 1, self.input_add_areaName)
                    tableWidget.setItem(0, 2, QTableWidgetItem('物业类型：'))
                    self.input_add_areaType = QComboBox()
                    for item in areaType:
                        self.input_add_areaType.addItem(item)
                    self.input_add_areaType.setCurrentText(areaDict['area_type'])
                    self.input_add_areaType.setObjectName("input_add_areaType")
                    tableWidget.setCellWidget(0, 3, self.input_add_areaType)
                    tableWidget.setItem(0, 4, QTableWidgetItem('竣工时间：'))
                    self.input_add_finishTime = QDateEdit()
                    self.input_add_finishTime.setObjectName("input_add_finishTime")
                    self.input_add_finishTime.setDate(QDate.fromString(areaDict['finish_time'], "yyyy-MM-dd"))
                    tableWidget.setCellWidget(0, 5, self.input_add_finishTime)
                    tableWidget.setItem(1, 0, QTableWidgetItem('产权年限：'))
                    self.input_add_limitYear = QComboBox()
                    for item in limitYear:
                        self.input_add_limitYear.addItem(item)
                    self.input_add_limitYear.setObjectName("input_add_limitYear")
                    self.input_add_limitYear.setCurrentText(areaDict['limit_year'])
                    tableWidget.setCellWidget(1, 1, self.input_add_limitYear)
                    tableWidget.setItem(1, 2, QTableWidgetItem('建筑类型：'))
                    self.input_add_buildType = QComboBox()
                    for item in buildType:
                        self.input_add_buildType.addItem(item)
                    self.input_add_buildType.setObjectName("input_add_buildType")
                    self.input_add_buildType.setCurrentText(areaDict['build_type'])
                    tableWidget.setCellWidget(1, 3, self.input_add_buildType)
                    tableWidget.setItem(1, 4, QTableWidgetItem('开发商：'))
                    self.input_add_areaBuilder = QLineEdit()
                    self.input_add_areaBuilder.setObjectName("input_add_areaBuilder")
                    self.input_add_areaBuilder.setText(areaDict['area_builder'])
                    tableWidget.setCellWidget(1, 5, self.input_add_areaBuilder)
                    tableWidget.setItem(2, 0, QTableWidgetItem('小区地址：'))
                    tableWidget.setSpan(2, 1, 1, 5)
                    self.input_add_areaAddress = QLineEdit()
                    self.input_add_areaAddress.setObjectName("input_add_areaAddress")
                    self.input_add_areaAddress.setText(areaDict['area_address'])
                    tableWidget.setCellWidget(2, 1, self.input_add_areaAddress)
                    tableWidget.resizeRowsToContents()

                    self.images = ast.literal_eval(areaDict['area_images'])
                    print(self.images)
                    if self.images is not None:
                        rowNum = math.ceil(len(self.images) / self.imgCol)
                        tableWidget2 = self.tableWidget_2
                        tableWidget2.setColumnCount(self.imgCol)
                        tableWidget2.setRowCount(rowNum)
                        tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                        tableWidget2.verticalHeader().setDefaultSectionSize(150)

                        AsyncImageLoader(self.images, self.display_image)

                    self.uploadSuccess = self.images
                    self.btn_upload_area.clicked.connect(lambda _, uploadType='area': self.upload_images(uploadType))
                    self.btn_submit_area.clicked.connect(self.btn_submit_area_click)
                    self.btn_cancel_area.clicked.connect(self.btn_cancel_area_click)
                else:
                    QMessageBox().about(self, '提示', '数据加载失败')
                    return False

        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def btn_submit_area_click(self):
        try:
            data = {
                'areaName': self.input_add_areaName.text(),
                'areaType': self.input_add_areaType.currentText(),
                'finishTime': self.input_add_finishTime.text(),
                'limitYear': self.input_add_limitYear.currentText(),
                'buildType': self.input_add_buildType.currentText(),
                'areaBuilder': self.input_add_areaBuilder.text(),
                'areaAddress': self.input_add_areaAddress.text(),
                'areaImages': json.dumps(self.uploadSuccess)
            }
            field = {'areaName': '小区名称', 'areaType': '物业类型', 'finishTime': '竣工时间', 'limitYear': '产权年限',
                     'buildType': '建筑类型', 'areaAddress': '小区地址'}
            for f in field:
                if data[f] == '':
                    QMessageBox.about(self, '提示', '请输入' + field[f])
                    eval("self.input_add_%s.setFocus()" % (f))
                    return False

            if self.id > 0:
                url = constant.API_HOST + '/setting/area_update'
                kind = '修改'
                data['id'] = self.id
                res = api.put(self, url, data)
            else:
                url = constant.API_HOST + '/setting/area_add'
                kind = '添加'
                res = api.post(self, url, data)
            if res['data']:
                msg = kind + '成功'
            else:
                msg = kind + '失败，服务器错误'
            print(msg)
            QMessageBox.about(self, '提示', msg)
            if msg == kind + '成功':
                self.close()

        except json.decoder.JSONDecodeError as e:
            QMessageBox().about(self, '提示', '返回数据异常')

    def btn_cancel_area_click(self):
        self.hide()

    def click_image(self, pixmap):
        scene = QGraphicsScene()
        pixmap_item = QGraphicsPixmapItem(pixmap)
        scene.addItem(pixmap_item)

        self.graphicsView.raise_()
        self.graphicsView.setScene(scene)
        self.graphicsView.mousePressEvent = lambda _: self.click_graphicsView()
        self.graphicsView.show()

    def click_graphicsView(self):
        self.graphicsView.setScene(None)
        self.graphicsView.hide()

    def upload_images(self, uploadType):
        # 选择图片文件
        files, _ = QFileDialog.getOpenFileNames(self, "Select Images", QDir.homePath(), "Images (*.jpg *.png)")
        if files:
            for file in files:
                self.uploadThread = ImageUploaderThread(self.token, file, uploadType)
                self.uploadThread.finished.connect(self.on_upload_finished)  # 假设有一个处理上传结果的槽函数
                self.uploadThread.start()

    def on_upload_finished(self, res):
        json_dict = json.loads(res)
        print(json_dict)
        if json_dict['code'] == 0:
            print(json_dict['data'])
            print("Image uploaded successfully!")
            image_url = json_dict['data']['path']
            self.uploadSuccess.append(image_url)

            img_count = len(self.uploadSuccess)
            rowNum = math.ceil(img_count / self.imgCol)
            tableWidget2 = self.tableWidget_2
            tableWidget2.setColumnCount(self.imgCol)
            tableWidget2.setRowCount(rowNum)
            tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            tableWidget2.verticalHeader().setDefaultSectionSize(150)

            print(self.uploadSuccess)
            AsyncImageLoader(self.uploadSuccess, self.display_image, img_count)

        else:
            QMessageBox().about(self, '提示', '图片上传失败：' + json_dict['message'])
            print(json_dict['message'])
            print("Error uploading image!")

    def display_image(self, image, i):
        widget = QWidget()
        label = QLabel(widget)
        pixmap = QPixmap.fromImage(image)
        label.setPixmap(pixmap)
        label.setScaledContents(True)
        label.mouseDoubleClickEvent = lambda _, pixmap=pixmap: self.click_image(pixmap)

        label = QLabel(widget)
        label.setText("X")
        label.mousePressEvent = lambda _, i=i: self.del_image(i)

        row = math.floor(i / self.imgCol)
        col = i % self.imgCol

        self.tableWidget_2.setCellWidget(row, col, widget)
        print(f"Image from {i} loaded successfully")

    def del_image(self, i):
        self.uploadSuccess.pop(i)

        img_count = len(self.uploadSuccess)
        rowNum = math.ceil(img_count / self.imgCol)
        tableWidget2 = self.tableWidget_2
        tableWidget2.clear()
        tableWidget2.setColumnCount(self.imgCol)
        tableWidget2.setRowCount(rowNum)
        tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        tableWidget2.verticalHeader().setDefaultSectionSize(150)
        AsyncImageLoader(self.uploadSuccess, self.display_image)

    def closeEvent(self, event):
        self.window_closed.emit()